<script setup>
import {ref} from 'vue';

const selectedMenuIds = ref([])

// 已授权的菜单id
const menusList = ref([])

import * as menusApi from '@/api/menuApi.js'
import * as roleApi from '@/api/roleApi.js'
import {message} from 'ant-design-vue';
const currentRoleId = ref('')

const loading = ref(false)
const open = ref(false)


// const filterSelectedMenuIds = (menu) => {
//
//   if (menu.menuType === '1') {
//     menusList.value.forEach(m => {
//       if (m.parentId === menu.id) {
//         m.selected = true
//       }
//     })
//   } else {
//     menu.selected = true
//     let isALlSelected = true
//     menusList.value.forEach(x => {
//       if (x.parentId === menu.parentId) {
//         if (!x.selected) isALlSelected = false
//       }
//     })
//     if (isALlSelected) {
//       menusList.value.forEach(x => {
//         if (x.id === menu.parentId) {
//           x.selected = true
//         }
//       })
//     }
//   }
//
//
// }

const loadHasGrantedResources = (roleId) => {
  roleApi.fetchGrantedResources(roleId).then(res => {
    selectedMenuIds.value = res.map(x => x.menuId)
  })
}

const loadMenuTrees = () => {
  menusApi.fetchMenuTree().then(res => {
    menusList.value = res
  })
}

loadMenuTrees()

const doGrantResource = () => {
  loading.value = true
  if (selectedMenuIds.value.length === 0) {
    message.error('请选择资源')
    loading.value = false
    return;
  }

  let params = {
    roleId: currentRoleId.value,
    menuIds: selectedMenuIds.value
  }
  roleApi.grantResource(params).then(() => {
    message.success('分配成功')
  }).finally(() => loading.value = false)
}


const onOpen = (roleId) => {
  if (!roleId) {
    message.error('角色 id 为正常传递')
    return
  }
  currentRoleId.value =  roleId
  loadHasGrantedResources(roleId)
  open.value = true
}

const onClose = () => {
  open.value = false
}

defineExpose({
  onOpen
})




</script>

<template>

  <a-drawer
      title="授权资源"
      width="550px"
      :open="open"
      @close="onClose"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
  >

    <a-tree
        :tree-data="menusList"
        checkable
        blockNode
        v-model:checkedKeys="selectedMenuIds"
        defaultExpandAll
        :field-names="{
      children: 'children',
      key: 'id',
      title: 'name'
    }"
    >

    </a-tree>

    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button :loading="loading" type="primary" @click="doGrantResource">提交</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<style scoped>

</style>
